<?php

namespace App\Http\Controllers\Excel;

//use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExcelController extends Controller
{

    protected $detail;      //详细数据
    protected $width;       //宽
    protected $height;      //高

    public function __construct($width = [], $height = [])
    {
        $this->width = $width;
        $this->height = $height;
    }

    /**
     * 导出excel
     * @params $fileName   文件名
     * @params $head    文件头
     * @params $detail  详细信息
     * @params $filed   头字段
     */
    public function exportExcel($fileName = '', $head = [], $detail = [], $filed = [])
    {

        $this->detail = $this->getOperationData($detail, $filed);

        \Excel::create($this->fileName, function ($excel) use ($fileName, $head) {

            // Set the title
            $excel->setTitle($fileName);

            // Chain the setters
            $excel->setCreator('信息部')
                    ->setCompany('卡替');

            // Call them separately
            $excel->setDescription($fileName);

            //创建表
            $excel->sheet($fileName, function ($sheet) use ($head) {
                //设置边距
                $sheet->setPageMargin(array(
                    0.25, 0.30, 0.25, 0.30
                ));
                if (!empty($this->width)) {
                    $sheet->setWidth($this->width);
                }

                if (!empty($this->height)) {
                    $sheet->setHeight($this->height);
                }

                $sheet->rows(array_merge([$head], $this->detail), null, 'A1', true);
            });
        })->download('xlsx');
    }

    /**
     * 导入文件 返回数据
     * @param $path
     * @return mixed
     */
    public function importExcel($path)
    {
        $data = \Excel::load($path, function($reader) {
                    
                })->get();
        return $data;
    }

    /**
     * 获取返回数据
     * @param $detail
     * @param $filed
     * @return array
     */
    public function getOperationData($detail, $filed)
    {
        return $this->setOperationData($detail, $filed);
    }

    /**
     * 设置返回数据
     * @param $data
     * @param $filed
     * @return array
     */
    public function setOperationData($data, $filed)
    {
        foreach ($data as $v) {
            foreach ($filed as $t) {
                if (stripos($t, '.')) {
                    $d = explode('.', $t);
                    if (isset($v[$d[0]][$d[1]])) {
                        $c[] = $v[$d[0]][$d[1]];
                    }
                } else {
                    if (isset($v[$t])) {
                        $c[] = $v[$t];
                    }
                }
            }
            $detail[] = $c;
            $c = [];
        }
        return $detail;
    }

}
